<template>
  <a-input-search
      v-model:value="value"
      placeholder="input search text"
      enter-button="Search"
      size="large"
      @search="onSearch"
    />
  <a-table :columns="columns" :data-source="dataSource" bordered>
    <template #bodyCell="{ column, text, record }">
      <!-- 确定哪些字段可以编辑 -->
      <template v-if="['username', 'hobby'].includes(column.dataIndex)">
        <div>
          <a-input
            v-if="editableData[record.id]"
            v-model:value="editableData[record.id][column.dataIndex]"
            style="margin: -5px 0"
          />
          <template v-else>
            {{ text }}
          </template>
        </div>
      </template>
      <template v-else-if="column.dataIndex === 'operation'">
        <div class="editable-row-operations">
          <span v-if="editableData[record.id]">
            <a-typography-link @click="save(record.id)">Save</a-typography-link>
            <a-popconfirm title="Sure to cancel?" @confirm="cancel(record.id)">
              <a>Cancel</a>
            </a-popconfirm>
          </span>
          <span v-else>
            <a @click="edit(record.id)">Edit</a>
          </span>
        </div>
      </template>
    </template>
  </a-table>
</template>
<script lang="ts" setup>
import { cloneDeep } from 'lodash-es';
import { onMounted, reactive, ref } from 'vue';
import type { UnwrapRef } from 'vue';
const value = ref<string>('');

const onSearch = (searchValue: string) => {
  fetch('http://localhost:8080/user/' + searchValue)
    .then(res => res.json())
    //传递封装，下面的res = res.json()
    .then(res => {
      console.log(res);
      data.length = 0; //清空数组
      res.forEach((item: any, index: number) => {
        data.push({
          id: item.id,
          username: item.username,
          hobby: item.hobby.hobbyName,
        });
      });
      //深克隆  ...data 
      dataSource.value = cloneDeep(data);
    });

};
// MVVM效果， 样式
const columns = [
  {
    title: 'id',
    dataIndex: 'id',
    width: '25%',
    sorter: {
      compare: (a, b) => a.id - b.id,
      multiple: 3,  //排序优先级
    },
  },
  {
    title: 'username',
    dataIndex: 'username',
    width: '15%',
  },
  {
    title: 'hobby',
    dataIndex: 'hobby',
    width: '40%',
  },
  {
    title: 'operation',
    dataIndex: 'operation',
  },
];
//实体类
interface DataItem {
  id: number;
  username: string;
  hobbyId:number;
  hobby: object;
}
const data: DataItem[] = [];
onMounted(() => {
  fetch('http://localhost:8080/user/findAll')
    .then(res => res.json())
    //传递封装，下面的res = res.json()
    .then(res => {
      console.log(res);
      res.forEach((item: any, index: number) => {
        data.push({
          id: item.id,
          username: item.username,
          hobbyId: item.hobbyId,
          hobby: item.hobby.hobbyName,
        });
      });
      //深克隆  ...data 
      dataSource.value = cloneDeep(data);
    });
  }
)
const dataSource = ref(data);
// edit编辑行
const editableData: UnwrapRef<Record<string, DataItem>> = reactive({});

const edit = (id: string) => {
  //datasource中通过key 过滤想要的一行数据
  editableData[id] = cloneDeep(dataSource.value.filter(item => id === item.id)[0]);
  console.log(editableData[id]);

};
//更新 put
const save = (id: string) => {
  //foreach 遍历元素item 取出 item的id
  Object.assign(dataSource.value.filter(item => id === item.id)[0], editableData[id]);
  delete editableData[id].hobby;
  console.log("保存方法：", editableData[id]);

  fetch('http://localhost:8080/user/', {
    method: 'PUT',
    headers: {
      'Content-Type': 'application/json',
    },
    //把对象变成JSON字符串
    body: JSON.stringify(editableData[id]),
  })
    .then(res => res.json())
    .then(res => {
      console.log('修改结果', res);
    });
  //保存后数据传给后台

  delete editableData[id];

};
const cancel = (id: string) => {
  delete editableData[id];
};
</script>
<style scoped>
.editable-row-operations a {
  margin-right: 8px;
}
</style>